package com.pda.common_easy.pages.outbill.scanf;

import android.annotation.SuppressLint;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;

import com.fntech.m10a.gpio.M10A_GPIO;
import com.pda.common_easy.PDApp;
import com.pda.common_easy.R;
import com.pda.common_easy.beanout.ScanfBeanOut;
import com.pda.common_easy.boardcast.CustomReceiver;
import com.pda.common_easy.boardcast.ScannerInterface;
import com.pda.common_easy.fntech.io.service.IOManager;
import com.pda.common_easy.fntech.io.service.SoundManager;
import com.pda.common_easy.message.MessageBus;
import com.pda.common_easy.thread.CodeBeans;
import com.pda.common_easy.tools.StringUtils;
import com.public_module.basemvp.activity.BaseActivity;
import com.public_module.dialogs.ChooseDialog;
import com.public_module.tools.VoiceUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class OutScanfActivity extends BaseActivity<OutScanfModel, OutScanfView, OutScanfPresent> implements OutScanfView {
    private String TAG = "OutScanfActivity";

    @BindView(R.id.iv_title_left)
    ImageView ivTitleLeft;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rltitle)
    RelativeLayout rltitle;
    @BindView(R.id.tvbill)
    TextView tvbill;
    @BindView(R.id.tvname)
    TextView tvname;
    @BindView(R.id.login_id)
    EditText loginId;
    @BindView(R.id.logine)
    Button logine;
    @BindView(R.id.sws)
    Switch sws;
    @BindView(R.id.ivd)
    ImageView ivd;
    @BindView(R.id.ivxn)
    ImageView ivxn;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.tvres)
    TextView tvres;
    @BindView(R.id.tvs)
    TextView tvs;
    @BindView(R.id.tv0)
    TextView tv0;
    @BindView(R.id.tvwait)
    TextView tvwait;

    int scanfState = 0;
    boolean flag = true;
    boolean flagt = false;
    List<ScanfBeanOut.DataBean> listdata = new ArrayList<>();
    CustomReceiver customReceiver = null;
    OutScanfAdapter outScanfAdapter;
    String billID = "", billListID = "", productID = "-1";
    VoiceUtils voiceUtils;
    CodeBeans codeBeans = new CodeBeans();
    Thread upThread = null;
    boolean exit = false;
    ChooseDialog chooseDialog1;
    public static final int MSG_GOTBARCODE = 0;
    private String barCode = "";
    public static String encode = "UTF-8";
    public static SoundManager mSoundManager = new SoundManager();
    public static Lock lock = new ReentrantLock();

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {  //接收数据
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_GOTBARCODE:
                    byte[] ret = (byte[]) msg.obj;
                    try {
                        barCode = new String(ret, encode);
                        barCode = barCode.replace("+","");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    writeFile("/sys/class/gpio/gpio907/direction", "out");
                    if (barCode.length()>0){
                        writeFile("/sys/class/gpio/gpio907/value", "1");
                    }
                    mSoundManager.playSound();
                    if (scanfState == -1) {
                        voiceUtils.voiceWarn();
                        tvres.setText("网络异常,请检查网络");
                        return;
                    }
                    if (StringUtils.checkBoxCode(barCode) || StringUtils.checkCaseCode(barCode)) {
                        CodeBeans.Code cbean = new CodeBeans.Code();
                        cbean.setStr(barCode);
                        cbean.setFlag(flag);
                        cbean.setFlagx(flagt);
                        lock.lock();
                        codeBeans.addCode(cbean);
                        lock.unlock();
                        tvwait.setText(codeBeans.getCodes().size()+"");
                    } else {
                        voiceUtils.voiceWarn();
                        tvres.setText("数码长度不符");
                    }
                    break;
                default:
                    break;
            }
        }
    };

    protected void initdata() {
        tvTitle.setText("出库扫描");
        tvwait.setText(0+"");
        presenter.getDeatail(getIntent().getStringExtra(PDApp.billID));
        chooseDialog = new ChooseDialog(this, "是否开启删除条码", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog.dismiss();
                flag = false;
                ivd.setImageResource(R.mipmap.icon_check);
            }
        });

        chooseDialog1 = new ChooseDialog(this, "是否开启虚拟托", R.style.CommentDialog, new ChooseDialog.PriorityListener() {
            @Override
            public void setActivityText() {
                chooseDialog1.dismiss();
                flagt = true;
                ivxn.setImageResource(R.mipmap.icon_check);
            }
        });

        customReceiver = new CustomReceiver(
                new CustomReceiver.PListener1() {
                    @Override
                    public void setData(CustomReceiver.Dataa dataa) {
                        tvs.setText(dataa.getStr());
                        scanfState = dataa.getType();
                        if (scanfState == -1) {
                            tvs.setBackgroundResource(R.color.smalltext);
                        } else {
                            tvs.setBackgroundResource(R.color.green);
                        }
                    }
                },
                new CustomReceiver.PListener2() {
                    @Override
                    public void setText(String string) {
                    }
                });
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(customReceiver, filter);
        voiceUtils = new VoiceUtils(this);
        EventBus.getDefault().register(this);
        upThread = new Thread(new Runnable() {
            @Override
              public void run() {
                while (!exit){
                    if(codeBeans.getCodes().size()>0){
                        String code = codeBeans.getCodes().get(0).getStr();
                        boolean flag1 = codeBeans.getCodes().get(0).isFlag();
                        boolean flag2 = codeBeans.getCodes().get(0).isFlagx();
                        codeBeans.removeCode(codeBeans.getCodes().get(0));
                        if(flag1){
                            presenter.addCode(billID, billListID, productID, code ,flag2);
                        }else{
                            presenter.deleteCode(billID, billListID, productID, code,flag2);
                        }
                    }
                }
            }
        });
        upThread.start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_out_scanf);
        ButterKnife.bind(this);
        mSoundManager.initSounds(this);
        M10A_GPIO.BdPowerOn();
        IOManager.INSTANCE.InitCommA(handler);
        initdata();
    }

    @Override
    protected void onDestroy() {
        M10A_GPIO.BdPowerOff();
        IOManager.INSTANCE.DeInitCommA();
        super.onDestroy();
        if (customReceiver != null) {
            unregisterReceiver(customReceiver);
        }
        EventBus.getDefault().unregister(this);
        exit = true;
        upThread = null;
    }

    @Override
    public OutScanfModel createModel() {
        return new OutScanfModelImpl(this);
    }

    @Override
    public OutScanfView createView() {
        return this;
    }

    @Override
    public OutScanfPresent createPresenter() {
        return new OutScanfPresent();
    }


    @OnClick({R.id.iv_title_left, R.id.logine, R.id.ivd, R.id.ivxn})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;
            case R.id.ivd:
                if (flag) {
                    chooseDialog.show();
                } else {
                    flag = true;
                    ivd.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.ivxn:
                if (!flagt) {
                    chooseDialog1.show();
                } else {
                    flagt = false;
                    ivxn.setImageResource(R.mipmap.icon_nocheck);
                }
                break;
            case R.id.logine:
                if (scanfState == -1) {
                    voiceUtils.voiceWarn();
                    tvres.setText("网络异常,请检查网络");
                    return;
                }
                if (StringUtils.checkBoxCode(loginId.getText().toString()) || StringUtils.checkCaseCode(loginId.getText().toString())) {
                    CodeBeans.Code cbean = new CodeBeans.Code();
                    cbean.setStr(loginId.getText().toString());
                    cbean.setFlag(flag);
                    cbean.setFlagx(flagt);
                    codeBeans.addCode(cbean);
                    tvwait.setText(codeBeans.getCodes().size()+"");
                } else {
                    voiceUtils.voiceWarn();
                    tvres.setText("数码长度不符");
                }
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initView(List<ScanfBeanOut.DataBean> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                listdata = list;
                tvbill.setText(list.get(0).getBillCode());
                tvname.setText(list.get(0).getDesStoreName());
                billID = list.get(0).getBillID();
                outScanfAdapter = new OutScanfAdapter(OutScanfActivity.this, listdata);
                listview.setAdapter(outScanfAdapter);
            }
        });
    }

    @Override
    public void updateView(List<ScanfBeanOut.DataBean> list) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                listdata.clear();
                if (billListID.length() > 0) {
                    list.get(0).setCk(true);
                }
                listdata.addAll(list);
                outScanfAdapter.notifyDataSetChanged();
                loginId.setText("");
                tvres.setText("此数码处理完成");
                tvwait.setText(codeBeans.getCodes().size()+"");
            }
        });
    }

    @Override
    public void showres(String str) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                voiceUtils.voiceWarn();
                tvres.setText(str);
                tvwait.setText(codeBeans.getCodes().size()+"");
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onBaseMessageEvent(MessageBus messageBus) {
        for (int i = 0; i < listdata.size(); i++) {
            listdata.get(i).setCk(false);
        }
        if (messageBus.getValue() == 1) {
            listdata.get(messageBus.getIndex()).setCk(true);
            billListID = listdata.get(messageBus.getIndex()).getBillListID();
            productID = listdata.get(messageBus.getIndex()).getProductID();
        } else {
            listdata.get(messageBus.getIndex()).setCk(false);
            billListID = "";
            productID = "-1";
        }
        outScanfAdapter.notifyDataSetChanged();
    }

    private static void writeFile(String fileName, String writestr) {
        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = writestr.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {   //按键监听
        switch (keyCode) {
            case 80: { //scan键值
                writeFile("/sys/class/gpio/gpio907/direction", "out");
                break;
            }
            case KeyEvent.KEYCODE_BACK: {
                M10A_GPIO.BdPowerOff();
                IOManager.INSTANCE.DeInitComm();
                //System.exit(0);
                break;
            }
            case 121: {
                writeFile("/sys/class/gpio/gpio1022/value", "0");
                break;
            }
            case 24:
                mSoundManager.playSound();
                return false;
            case 25:
                mSoundManager.playSound();
                return false;
        }
        return true;
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case 80:{
                writeFile("/sys/class/gpio/gpio907/value", "1");
                break;
            }
            case 121: {
                writeFile("/sys/class/gpio/gpio1022/value", "1");
                break;
            }
        }
        return true;
    }
}
